<?php

/*
	$param :
		"heading" 		: page heading title
		"heading_img"	: page heading image
		"database"		: object derived from spFormDatabase
		"formbuilder"	: object derived from spFormBuilder
*/
	
require_once "form/spFormButtons.php";
	
class spPageOptions extends spPage
{
	private $param;
	private $formBuilder;

	public function __construct( $param )
	{
		$this->param = $param;
		parent::__construct();
	}
	
	public function init()
	{
		$heading 		= isset($param["heading"])?$param["heading"]:"";
		$heading_img 	= isset($param["heading_img"])?$param["heading_img"]:null;
	
		parent::addClass( "spPageOptions" );
		parent::addAttr( "data-database", 		$this->param["database"] );
		parent::addAttr( "data-formbuilder", 	$this->param["formbuilder"] );

		parent::spRenderDefaults();
		parent::spRenderHeading( $heading, $heading_img );
		
		$this->createFormBuilderAndDatabase();
	}
	
	// override this to add to tab pages
	public function createFormBuilderAndDatabase()
	{
		$param = $this->param;
		$this->formBuilder = new $param["formbuilder"];
		$this->formBuilder->setDatabase( new $param["database"] );
		$this->formBuilder->setFormButtonsBottom(new spFormButtons(array(
			array( 
				"class"		=> "spSaveOption",
				"value" 	=> "Save"
			)
		)));	
	
		parent::addChild( $this->formBuilder );
	}	
		
	public function render()
	{
		parent::render();
	}
}

function spAjaxOptionsSave()
{
	$_REQUEST = unMagicQuotify($_REQUEST);

	$db = $_REQUEST["database"];
	$database = new $db;

	$database->updateFromRequest();
	if ( !$database->save() )
	{
		$errors = $database->getFormErrors();
		$json = array(
			"formerrors" => $errors
		);
		echo json_encode( $json );
		return;
	}
	
	echo "{}";
}

?>